package com.example.mcdonaldapplication.activity

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mcdonaldapplication.databinding.ActivityIndentDetailBinding
import com.example.mcdonaldapplication.info.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import kotlin.concurrent.thread


class IndentDetailActivity : AppCompatActivity() {
    private lateinit var binding: ActivityIndentDetailBinding
    private val indentDetailList = ArrayList<IndentDetailInfo>()
    private val goodsList = ArrayList<GoodsInfo>()
    private val serverIP = ServerIP.getIp()
    private var i = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityIndentDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.hide()
        initView()
    }

    @SuppressLint("SetTextI18n")
    private fun initView(){
        //获取合计价格
        val totalPrice = intent.getIntExtra("price",0)
        binding.tvTotalPrice4.text ="¥${totalPrice}"    //商品小计

        getAllGoods()
        binding.rvIndent.layoutManager = LinearLayoutManager(this)
        binding.rvIndent.adapter = IndentDetailAdapter(indentDetailList)
        val address = intent.getStringExtra("address")  //获取地址
        binding.tvIndentAddress.text = address.toString()
        //判断外卖/堂食
        if(address != null){
            binding.ccIndentAddress.visibility = View.VISIBLE
        }else{
            binding.ccIndentAddress.visibility = View.GONE
        }
        binding.tvConfirm.setOnClickListener {
            val editor = getSharedPreferences("cart", Context.MODE_PRIVATE).edit()
            editor.clear()
            editor.apply()
            finish()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun getAllGoods(){
        thread {
            val formBody: FormBody = FormBody.Builder()
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIP}/goods/queryAll")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            parseJSONGetIntentDetail(responseData)
            runOnUiThread{
                binding.rvIndent.adapter?.notifyDataSetChanged()
            }
        }
    }

    private fun parseJSONGetIntentDetail(jsonData: String) {
        val jsonObject = JSONObject(jsonData)
        val message = jsonObject.getString("message")
        val data = jsonObject.getString("data")
        if (message == "查询成功") {
            val gson = Gson()
            val typeOf = object : TypeToken<List<GoodsInfo>>() {}.type
            val goodsInfoList = gson.fromJson<List<GoodsInfo>>(data, typeOf)
            for (good in goodsInfoList) {
                goodsList.add(good)
            }
            val prefs = getSharedPreferences("cart", Context.MODE_PRIVATE)
            i = 0
            for (goods in goodsList) {
                val num = prefs.getInt("${goods.name}num", 0)
                val price = prefs.getString("${goods.name}price", "0")!!
                val totalPrice = price.toInt() * num
                val img = prefs.getString("${goods.name}img", "0")!!
                if (num >= 1) {
                    indentDetailList.add(i, IndentDetailInfo(goods.name, num, totalPrice.toString(), img))
                    i++
                }
            }
        }
    }
}